<template>
  <div class="container">
    <div>
      <el-row :gutter="20">
        <el-col :span="5">
          <el-form ref="form" :model="form">
            <el-form-item label="车辆号牌：">
              <el-input
                v-model="select.CPH"
                placeholder="请输入车牌"
                style="width: 150px"
              ></el-input>
            </el-form-item>
          </el-form>
        </el-col>
        <!-- <el-col :span="9">
          <el-form ref="form" :model="form">
            <el-form-item label="日期：" :label-width="labelwidth">
              <el-date-picker
                v-model="value2"
                type="daterange"
                align="right"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="mini"
                :picker-options="pickerOptions"
              >
              </el-date-picker>
            </el-form-item>
          </el-form>
        </el-col> -->
        <!-- <el-col :span="6">
          <el-form ref="form" :model="form">
            <el-form-item label="车况：">
              <el-select v-model="form.statusValue" placeholder="请选择车辆情况">
                <el-option
                  v-for="(item,index) in form.statusList"
                  :value="item.label"
                  :label="item.value"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-col> -->
        <!-- <el-col :span="6" v-if="form.timeTypeValue === '0'">
          <el-form ref="form" :model="form">
            <el-form-item label="结束日期：" class="wid50">
              <el-date-picker
                v-model="form.endDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-form>
        </el-col>-->
        <el-col :span="8">
          <el-form ref="form" :model="form" style="float: left">
            <el-form-item>
              <el-button size="mini" type="primary" @click="screeningData"
                >查 询</el-button
              >
              <el-button size="mini" type="success" @click="handleAdd"
                >新 增</el-button
              >
              <el-button style="padding: 0; border: 0">
                <el-upload
                  action="/上传文件的接口"
                  :on-change="onChange"
                  :auto-upload="false"
                  :show-file-list="false"
                  accept=".xls, .xlsx"
                  class="upload"
                >
                  <el-button size="mini" type="success">导 入</el-button>
                </el-upload>
              </el-button>
              <el-button size="mini" type="warning" @click="exportExcel"
                >导 出</el-button
              >
              <!-- <el-button size="mini" type="success" @click="exportExcel">删 除</el-button> -->
            </el-form-item>
            <!-- <el-form-item>
              <el-form ref="form" :model="form" style="float:left">
              <el-button size="mini" type="success" @click="exportExcel">导 入</el-button>
              <el-button size="mini" type="success" @click="exportExcel">导 出</el-button>
            </el-form-item> -->
          </el-form>
        </el-col>
      </el-row>
    </div>
    <el-table
      highlight-current-row
      :data="
        tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
      "
    >
      <el-table-column
        prop="ID"
        label="保养记录编号"
        align="center"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="CPH"
        label="车牌照号"
        align="center"
        width="170"
      ></el-table-column>
      <el-table-column
        prop="MAINTAINTIME"
        label="实际保养时间"
        align="center"
        width="170"
      ></el-table-column>
      <el-table-column
        prop="MAINTAINMILEAGE"
        label="实际保养里程"
        align="center"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="MAINTAINPERSON"
        label="保养人员"
        align="center"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="REMARK"
        label="保养说明"
        align="center"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="ZT"
        label="状态"
        align="center"
        width="100"
      ></el-table-column>
      <el-table-column
        prop="MAINTAINPRICE"
        label="保养花费金额"
        align="center"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="YMAINTAINTIME"
        label="应保养时间"
        align="center"
        width="170"
      ></el-table-column>
      <el-table-column
        prop="NEXTMAINTAINTIME"
        label="下次保养时间"
        align="center"
        width="170"
      ></el-table-column>
      <el-table-column
        prop="NEXTMAINTAINMILEAGE"
        label="下次保养里程"
        align="center"
        width="120"
      ></el-table-column>
      <el-table-column
        prop="YMAINTAINMILEAGE"
        label="应保养里程"
        align="center"
        width="120"
      ></el-table-column>
      <el-table-column label="保养单照片" width="100px" align="center">
        <template slot-scope="scope">
          <el-image
            style="width: 45px; height: 45px; margin-top: 5px"
            :src="scope.row.BYFJPATH"
            @click="bigImage(scope.row)"
          >
            <div slot="error" class="image-slot" style="margin-top: 10px">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            type="text"
            @click="handleDelete(scope.$index, scope.row)"
            style="color: red"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="tableData.length"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      ></el-pagination>
    </div>
    <!-- 图片放大 -->
    <el-dialog
      title="图片展示"
      :visible.sync="showBigDialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-image style="width: 100%; height: 100%" :src="srcBig"></el-image>
    </el-dialog>
    <!-- 弹出框 -->
    <el-dialog
      :title="addDialogTitle"
      :visible.sync="isVisibleEdit"
      width="50%"
    >
      <el-form ref="form" :model="form" label-width="5.729vw" class="flex">
        <el-form-item label="车牌照号：" class="wid50">
          <el-input
            v-model="form.CPH"
            placeholder="请输入车牌照号"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="实际保养时间：" class="wid50">
          <el-date-picker
            v-model="form.MAINTAINTIME"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="实际保养里程：" class="wid50">
          <el-input
            v-model="form.MAINTAINMILEAGE"
            placeholder="请输入实际保养里程"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="保养人员：" class="wid50">
          <el-input
            v-model="form.MAINTAINPERSON"
            placeholder="请输入保养人员"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="保养说明：" class="wid50">
          <el-input
            v-model="form.REMARK"
            placeholder="请输入保养说明"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态：" class="wid50">
          <el-input
            v-model="form.ZT"
            placeholder="请输入状态"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="保养花费金额：" class="wid50">
          <el-input
            v-model="form.MAINTAINPRICE"
            placeholder="请输入保养花费金额"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="应保养时间：" class="wid50">
          <el-date-picker
            v-model="form.YMAINTAINTIME"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="下次保养时间：" class="wid50">
          <el-date-picker
            v-model="form.NEXTMAINTAINTIME"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="下次保养里程：" class="wid50">
          <el-input
            v-model="form.NEXTMAINTAINMILEAGE"
            placeholder="请输入下次保养里程"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="应保养里程：" class="wid50">
          <el-input
            v-model="form.YMAINTAINMILEAGE"
            placeholder="请输入应保养里程"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="保养单照片：">
          <input type="file" ref="file" />
        </el-form-item> -->
        <el-form-item label="保养单照片：" class="wid50">
            <el-button size="mini" type="success" @click="clickBYFJPic">

            <span v-if="this.BYFJPicUrl">重新上传</span>
            <span v-else>上传图片</span>
          </el-button>
          <span style="margin-left: 50px" v-if="this.BYFJPicUrl">{{
            this.BYFJPicUrl
          }}</span>
          <span style="margin-left: 50px" v-else>{{ form.BYFJPATH }}</span>
          <input
            type="file"
            ref="BYFJPicFile"
            style="display: none"
            accept="image/gif, image/jpeg"
            @change="changeBYFJPic"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisibleEdit = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import '@/assets/css/common.css'

import export2Excel from '@/utils/exportExcel/index.js'
import OSS from 'ali-oss';
import { time } from 'echarts';



export default {
  data () {

    return {
      clientData: [],
      currentPage: 1, //初始页
      pageSize: 10,    //    每页的数据
      originalData: [],
      tableData: [],
      select: {
        CPH: ''
      },
      isVisibleEdit: false,
      form: {
        CPH: "",
        MAINTAINTIME: "",
        MAINTAINMILEAGE: "",
        MAINTAINPERSON: "",
        REMARK: "",
        ZT: "",
        MAINTAINPRICE: "",
        NEXTMAINTAINTIME: "",
        YMAINTAINTIME: "",
        NEXTMAINTAINMILEAGE: "",
        YMAINTAINMILEAGE: "",
        BYFJPATH: "",
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近六个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 180);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一年',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
            picker.$emit('pick', [start, end]);
          }
        },]
      },
      showBigDialogVisible: false,
      srcBig: '',
      //图片上传
      fileList: [],
      BYFJPicUrl: '', //存上传后的车辆副本照片url
      dataObj: {
        region: 'oss-cn-beijing',//我的存储是北京，可根据具体配置自行修改
        accessKeyId: 'LTAISI12uxTRFccz',
        accessKeySecret: 'cQAvLIZ9JizT5RXRNPBVcXfg3iURD8',
        bucket: 'photo-srw-hb2',
      }, //存签名信息
      baseAli: 'oss-cn-beijing.aliyuncs.com',
    }
  },
  created () {
    if (localStorage.getItem('CTYPE') == '0') {
      this.rolelevel.shift()
    } else if (localStorage.getItem('CTYPE') != '-1') {
      this.rolelevel = []
    }
    this.getClientRoleList()
  },
  mounted () {
    this.getlistdata()
    this.getClientRoleList()

  },
  methods: {
    //获取保养信息列表
    async getlistdata () {
      var url = '/CarService/GetCarMaintainInfo?CLIENT_NO=' + localStorage.getItem('CLIENT_NO')
      const { data } = await this.$Http.get(url)
      this.originalData = data
      this.screeningData()
    },
    // 导入Excel
    onChange (file, fileList) {
      //  console.log(fileList);
      this.fileData = file; // 保存当前选择文件
      this.readExcel(); // 调用读取数据的方法
    },
    // 读取数据
    readExcel (e) {
      let that = this;
      const files = that.fileData;
      console.log(files);
      if (!files) {
        //如果没有文件
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
        this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }
      const fileReader = new FileReader();
      console.log(fileReader)
      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          //  console.log(ev.target)
          //  console.log(this);
          const workbook = this.XLSX.read(data, {
            type: "binary"// 以字符编码的方式解析
          });

          if (workbook.SheetNames.length >= 1) {
            //  this.$message({
            //    message: "导入数据表格成功",
            //    showClose: true,
            //    type: "success"
            //  });

            const wsname = workbook.SheetNames[0]; //取第一张表
            const ws = this.XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
            console.log(ws)
            this.inputExcelDataLength = ws.length
            this.fullscreenLoading = this.$loading({
              lock: true,
              text: 'Loading',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            })
            for (let i = 0, len = ws.length; i < len; i++) {
              var item = ws[i]
              //   var sheetData = {
              //     VID: item['居民电话'],
              //     RUBBISH_NAME: item["垃圾品名"],
              //     WEIGHT: item["垃圾称重"],
              //     photo: '',
              //     LONGITUDE: 0,
              //     LATITUDE: 0
              //   }
              //   let exceldata =  []
              //   exceldata.push(sheetData)
              this.addWeight(item)
            }
          } else {
            this.$message.error("未读取到表格内容");
          }
        } catch (e) {
          return false;
        }
      };
      // 如果为原生 input 则应是 files[0]
      fileReader.readAsBinaryString(files.raw);
    },
    async addWeight (item) {
      this.$axios({
        url: 'CarService/AddCarMaintainInfo',
        method: 'post',
        data: {
          CPH: item['车牌照号'],
          MAINTAINTIME: item['实际保养时间'],
          MAINTAINMILEAGE: item['实际保养里程'],
          MAINTAINPERSON: item['保养人员'],
          REMARK: item['保养说明'],
          ZT: item['状态'],
          MAINTAINPRICE: item['保养花费金额'],
          NEXTMAINTAINTIME: item['下次保养时间'],
          YMAINTAINTIME: item['应保养时间'],
          NEXTMAINTAINMILEAGE: item['下次保养里程'],
          YMAINTAINMILEAGE: item['应保养里程'],
          BYFJPATH: "",
        }
      }).then(res => {
        console.log(res)
        this.inputExcelDataIndex++
        if (res.data.IsSucess) {
          this.fullscreenLoading.close()
          this.$message.success('表格文件导入成功')
          this.getlistdata()
        } else {
          this.fullscreenLoading.close()
          this.$message.error('表格文件导入失败' + '，' + res.data.Message);
        }
        if (this.inputExcelDataIndex == this.inputExcelDataLength) {
          this.fullscreenLoading.close()
          if (this.strError.length == 0) {
            this.$message.success('表格文件导入成功')
            this.getlistdata()
          } else {
            // this.$message.error('表格文件导入结束<br/>' + this.strError);
            this.$message({
              message: '表格文件导入结束，' + this.strError,
              type: 'error',
              duration: 5000
            })
          }
          this.getlistdata()
        }
      })
      //   })
    },
    // 导出Excel
    exportExcel () {
      let excelName = '车辆保养记录'
      const tHeader = ['保养记录编号', '车牌照号', '实际保养时间', '实际保养里程', '保养人员', '保养说明', '状态', '车保养花费金额龄', '下次保养时间', '应保养时间'
        , '下次保养里程', '应保养里程', '保养单照片']
      const filterVal = ['ID', 'CPH', 'MAINTAINTIME', 'MAINTAINMILEAGE', 'MAINTAINPERSON', 'REMARK', 'ZT', 'MAINTAINPRICE', 'NEXTMAINTAINTIME', 'YMAINTAINTIME'
        , 'NEXTMAINTAINMILEAGE', 'YMAINTAINMILEAGE', 'BYFJPATH']
      export2Excel(tHeader, filterVal, this.tableData, excelName)
    },
    // 打开新增窗口
    handleAdd () {
      this.addDialogTitle = '新增车辆保养信息'
      //清空编辑框
      this.form = {
        CPH: "",
        MAINTAINTIME: "",
        MAINTAINMILEAGE: "",
        MAINTAINPERSON: "",
        REMARK: "",
        ZT: "",
        MAINTAINPRICE: "",
        NEXTMAINTAINTIME: "",
        YMAINTAINTIME: "",
        NEXTMAINTAINMILEAGE: "",
        YMAINTAINMILEAGE: "",
        BYFJPATH: "",
      }
      //展示窗口
      this.isVisibleEdit = true;
      // this.idEdit = false;
    },
    // 打开编辑窗口
    handleEdit (index, row) {
      this.form = Object.assign({}, row);
      this.addDialogTitle = '编辑车辆保养信息'
      this.isVisibleEdit = true;
    },
    // 点击保存，判断是新增还是编辑操作
    handleSubmit () {
      if (this.addDialogTitle == '新增车辆保养信息') {
        this.saveAdd()
      } else {
        this.saveEdit()
      }
    },
    // 新增保存
    async saveAdd () {
      // console.log(this.addform);
      this.$axios({
        url: 'CarService/AddCarMaintainInfo',
        method: 'post',
        data: {
          CPH: this.form.CPH,
          MAINTAINTIME: this.form.MAINTAINTIME,
          MAINTAINMILEAGE: this.form.MAINTAINMILEAGE,
          MAINTAINPERSON: this.form.MAINTAINPERSON,
          REMARK: this.form.REMARK,
          ZT: this.form.ZT,
          MAINTAINPRICE: this.form.MAINTAINPRICE,
          NEXTMAINTAINTIME: this.form.NEXTMAINTAINTIME,
          YMAINTAINTIME: this.form.YMAINTAINTIME,
          NEXTMAINTAINMILEAGE: this.form.NEXTMAINTAINMILEAGE,
          YMAINTAINMILEAGE: this.form.YMAINTAINMILEAGE,
          BYFJPATH: this.BYFJPicUrl,
        }
      }).then((res) => {
        console.log(res)
        if (res.data.IsSucess) {
          this.$message.success('新增成功');
          this.isVisibleEdit = false
          this.getlistdata()
        } else {
          this.$message.error('新增失败');
        }
      })
    },
    // 保存编辑
    async saveEdit () {
      let PATH = ''
      if (this.BYFJPicUrl === '') {
        //未做选择修改
        PATH = this.form.BYFJPATH
      } else {
        PATH = this.BYFJPicUrl
      }
      this.$axios({
        url: 'CarService/UpdataCarMaintainInfo',
        method: 'post',
        data: {
          ID: this.form.ID,
          CPH: this.form.CPH,
          MAINTAINTIME: this.form.MAINTAINTIME,
          MAINTAINMILEAGE: this.form.MAINTAINMILEAGE,
          MAINTAINPERSON: this.form.MAINTAINPERSON,
          REMARK: this.form.REMARK,
          ZT: this.form.ZT,
          MAINTAINPRICE: this.form.MAINTAINPRICE,
          NEXTMAINTAINTIME: this.form.NEXTMAINTAINTIME,
          YMAINTAINTIME: this.form.YMAINTAINTIME,
          NEXTMAINTAINMILEAGE: this.form.NEXTMAINTAINMILEAGE,
          YMAINTAINMILEAGE: this.form.YMAINTAINMILEAGE,
          BYFJPATH: PATH,
        },

      }).then((res) => {
        console.log(this.data)
        console.log(res)
        if (res.data.IsSucess) {
          this.$message.success('编辑成功');
          this.isVisibleEdit = false
          this.getlistdata()
        } else {
          this.$message.error('编辑失败');
        }
      })
    },
    // 删除车辆信息
    async handleDelete (index, row) {
      const confirmResult = await this.$confirm('确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult == 'confirm') {
        const params = {
          ID: row.ID,
        }
        const { data } = await this.$Http.get('CarService/DeleteCarMaintainInfo', { params })
        if (data.IsSucess) {
          this.$message.success('删除成功')
          this.isVisibleEdit = false
          this.getRoleList()
        }else {
            this.$message.error('删除失败');
          }  
      }else{
        this.$message.info('取消删除')
        this.isVisibleEdit = false
      }
      
    },
    // 模糊查询
    screeningData () {
      this.currentPage = 1;
      this.tableData = this.originalData
      if (this.select.CPH) this.tableData = this.tableData.filter(item => item.CPH.includes(this.select.CPH))
    },
    // 分页导航
    handlePageChange (currentPage) {
      this.currentPage = currentPage;
      // console.log(this.currentPage)
      // this.$set(this.query, 'pageIndex', val);
      // this.getlistdata();
    },
    handleSizeChange (size) {
      this.pageSize = size;
      console.log(this.pageSize)
    },
    // 放大图片
    bigImage (row) {
      this.srcBig = row.BYFJPATH
      this.showBigDialogVisible = true
    },
    handleClose () {
      this.showBigDialogVisible = false;
    },
    // 限制用户上传的图片格式和大小
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 点击上传保养单图片按钮
    clickBYFJPic () {
      this.$refs.BYFJPicFile.click();
    },
    changeBYFJPic () {
      this.afterRead(this.$refs.BYFJPicFile.files[0]);
      this.$refs.BYFJPicFile.value = null; // 移除文件，可以保证上传同样的文件时，也会触发change事件
    },
    afterRead (file) {
      return new Promise((resolve, reject) => {
        // 此时可以自行将文件上传至服务器
        const that = this
        let client = new OSS(this.dataObj)
        const fileName = file.name
        //定义唯一的文件名，打印出来的uid其实就是时间戳
        //client 是第一步中的 client
        client
          .multipartUpload(fileName, file)
          .then((result) => {
            //下面是如果对返回结果再进行处理，根据项目需要
            // console.log(result)
            that.BYFJPicUrl =
              'http://' +
              result.bucket +
              '.' +
              that.baseAli +
              '/' +
              result.name
            console.log(that.tempUrl)
            resolve()
          })
          .catch((err) => {
            console.log('err:', err)
            reject()
          })
      })
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    }
  }
}
</script>
<style>
.content {
  overflow-y: scroll;
}
.el-col-6 {
  width: 350px;
  min-height: 50px;
}
.el-table th {
  height: 40px;
}
.el-form-item label {
  width: 80px;
}
</style>